<template>
  <div class="doctor-management-container">
    <el-card class="box-card">
      <div class="header">
        <h2>医生管理</h2>
      </div>

      <!-- 查询条件区域 -->
      <div class="query-form">
        <h3>查询条件</h3>
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="医生姓名：">
            <el-input v-model="queryParams.name" placeholder="请输入医生姓名" clearable />
          </el-form-item>
          <el-form-item label="医院名称：">
            <el-input v-model="queryParams.hospitalName" placeholder="请输入医院名称" clearable />
          </el-form-item>
          <el-form-item label="一级科室：">
            <el-select v-model="queryParams.department" placeholder="全部" clearable>
              <el-option
                  v-for="item in departmentOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 功能按钮组 -->
      <div class="action-buttons">
        <el-button type="primary" size="small" @click="handleAdd">+ 添加</el-button>
        <el-button size="small" @click="handleBatchDelete" :disabled="!selection.length">删除</el-button>
        <el-button size="small" @click="handleBatchOnline" :disabled="!selection.length">上架</el-button>
        <el-button size="small" @click="handleBatchOffline" :disabled="!selection.length">下架</el-button>
      </div>

      <!-- 医生列表 -->
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="医生姓名" width="120"/>
          <el-table-column prop="avatar" label="医生头像" width="120"/>
        <el-table-column prop="title" label="医生职称" width="120" />
        <el-table-column prop="hospitalName" label="所属医院" width="180" />
        <el-table-column prop="departmentName" label="所属科室" width="180" />
        <el-table-column prop="status" label="是否上架" width="100">
          <template #default="{row}">
            <el-switch
                v-model="row.status"
               :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button size="small" @click="handleViewDetail(row)">查看详情</el-button>
            <el-button size="small" type="primary" @click="handleSetRegistration(row)">设置挂号预约</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页插件 ========================================== =============================== -->
      <div class="demo-pagination-block">
        <!--
                    1. current-page  ： 当前页   （重要）
                    2. page-size  : 每页显示条数（重要）
                    3. page-sizes ： 分页类型
                    4. small： 字体大小
                    5. disabled： 是否可用
                    6. background： 按钮颜色
                    7. total： 总数据条数（重要）

            -->
        <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[2, 3, 4, 5]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"></el-pagination>
      </div>
      <!-- 分页插件 ========================================== =============================== -->

    </el-card>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {router} from "@/router/index.js";



// 科室选项
const departmentOptions = ref([])
const getlevel1Departments=()=>{
  axios.get("/doctor/getDartment").then(res=>{
    departmentOptions.value = res.data.obj.map(item=>({
      value: item,
      label: item
    }))
  })
}


// 表格数据
const tableData = ref([])
const getDoctors=()=>{
  axios.get(`/doctor/getDoctor/${pageNum.value}/${pageSize.value}`).then(res=>{
 tableData.value = res.data.obj.records;
    total.value = res.data.obj.total;
    ElMessage.success('查询成功');
  })
}
onMounted(()=>{
  getDoctors();
  getlevel1Departments();
})
// 分页模型定义=======================================================================
let pageNum = ref(1);
let pageSize = ref(3);
let total = ref(1);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);
const handleSizeChange = (val) => {
  pageSize.value = val;
  getDoctors();
}
const handleCurrentChange = (val) => {
  // 将这个val数字赋值给 pageNum
  pageNum.value = val;
  getDoctors();
}
// 分页模型定义=======================================================================

// 查询方法
// 查询参数
const queryParams = reactive({
  name: '',
  hospitalName: '',
  department: ''
})
const handleQuery = () => {
  // 构造符合Hospital对象的查询参数
  const searchParams = {
    name: queryParams.name,
    hospitalName: queryParams.hospitalName,
    department: queryParams.department
  }

  axios.post(`/doctor/searchDoctor/${pageNum.value}/${pageSize.value}`, searchParams, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(res => {
    tableData.value = res.data.obj.records;
    total.value = res.data.total
    ElMessage.success('查询成功')
  }).catch(error => {
    ElMessage.error('查询失败: ' + error.message)
  })
}

const handleReset = () => {
  queryParams.value = {
    name: '',
    hospitalName: '',
    department: ''
  }
  handleQuery()
}

// 批量操作方法
const selection = ref([])
const handleBatchDelete = () => {
  if (selection.value.length === 0) return;
  ElMessageBox.confirm('确定要删除选中的医生吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 1. 提取ID数组
    const ids = selection.value.map(item => item.id)

    // 2. 发送请求
    axios.post('/doctor/batchDeleteDoctor', ids, {
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        getDoctors() // 刷新列表
        selection.value = [] // 清空选中项
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    }).catch(error => {
      ElMessage.error('删除失败: ' + error.message)
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchOnline = () => {
  if (selection.value.length === 0) return;
  ElMessageBox.confirm('确定要上架选中的医生吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selection.value.map(item => item.id);
      const response = await axios.post('/doctor/batchUpdateStatus', {
        ids: ids,
        status: 1 // 上架状态
      });

      if (response.data.code === 200) {
        ElMessage.success(`已成功上架${selection.value.length}个医生`);
        getDoctors(); // 刷新列表
        selection.value = []; // 清空选中项
      } else {
        ElMessage.error( '批量上架失败');
      }
    } catch (error) {
      ElMessage.error('批量上架失败: ');
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
}

const handleBatchOffline = () => {
  if (selection.value.length === 0) return;

  ElMessageBox.confirm('确定要下架选中的医院吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selection.value.map(item => item.id);
      const response = await axios.post('/doctor/batchUpdateStatus', {
        ids: ids,
        status: 0 // 下架状态
      });

      if (response.data.code === 200) {
        ElMessage.success(`已成功下架${selection.value.length}个医生`);
        getDoctors(); // 刷新列表
        selection.value = []; // 清空选中项
      } else {
        ElMessage.error( '批量下架失败');
      }
    } catch (error) {
      ElMessage.error('批量下架失败: ');
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
}

// 表格方法
const handleSelectionChange = (val) => {
  selection.value = val
}

const handleStatusChange = async(row) => {
  try {
    const response = await axios.post('/doctor/updateStatus', {
      id: row.id,
      status: row.status
    });
    if (response.data.code === 200) {
      const action = row.status === 1 ? '上架' : '下架';
      ElMessage.success(`已${action}医生: ${row.name}`);
      getDoctors(); // 刷新列表
    } else {
      // 失败时恢复原状态
      row.status = row.status === 1 ? 0 : 1;
      ElMessage.error( '状态更新失败');
    }
  } catch (error) {
    // 失败时恢复原状态
    row.status = row.status === 1 ? 0 : 1;
    ElMessage.error('状态更新失败: ');
  }
}

const handleViewDetail = (row) => {
  router.push(`/doctorDetail/${row.id}`)
  ElMessage.info(`查看医生: ${row.name} 的详情`)
  // 跳转到详情页或打开详情弹窗
}

const handleSetRegistration = (row) => {
  console.log('设置挂号:', row.id)
  // 打开设置挂号弹窗
}
const handleAdd=()=>{
  router.push('addDoctor')
}




</script>

<style scoped>
.doctor-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.box-card {
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.query-form {
  background-color: #f9f9f9;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.query-form h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.action-buttons {
  margin-bottom: 15px;
}

.doctor-info {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}
</style>